using FluentValidation;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Specifications;
using Zhaoxi.Zhihu.SharedKerel.Messaging;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;
using Zhaoxi.Zhihu.SharedKerel.Result;
using Zhaoxi.Zhihu.UseCases.Common.Attributes;
using Zhaoxi.Zhihu.UseCases.Common.Interface;

namespace Zhaoxi.Zhihu.UseCases.Answers.Command;

[Authorize]
public record DeleteAnswerComnand(int QuestionId, int AnswerId) : ICommand<Result>;

public class DeleteAnswerCommandValidator : AbstractValidator<DeleteAnswerComnand>
{
    public DeleteAnswerCommandValidator()
    {
        RuleFor(conmand=>conmand.QuestionId)
            .GreaterThan(0);
        RuleFor(command=>command.AnswerId)
            .GreaterThan(0);
    }
}
public class DeleteAnswerCommandHandler(
    IRepository <Question> questions,
    IUser user) : ICommandHandler<DeleteAnswerComnand, Result>
{
    public async Task<Result> Handle(DeleteAnswerComnand request, CancellationToken cancellationToken)
    {
        var spec = new AnswerByIdAndCreatedBySpec(user.Id!.Value, request. QuestionId,
            request.AnswerId);
        var question = await questions.GetSingleOrDefaultAsync(spec, cancellationToken);
        if (question == null) return Result. NotFound("问题不存在");
        var answer = question.Answers.FirstOrDefault(a => a.Id == request.AnswerId);
        if (answer == null) return Result.NotFound("回答不存在");
        
        question.Answers. Remove(answer);
        await questions.SaveChangesAsync(cancellationToken);
        return Result.Success();
    }
}
